<template>
  <div class="app-container">
    <!-- 添加或修改OA 请假申请对话框 -->
    <el-dialog :title="title" v-model="open" width="850px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" :disabled="disabled">
        <el-form-item label="申请人" prop="creatorName">
          <el-input v-model="form.creatorName" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item label="政策标题" prop="title">
          <el-input v-model="form.title" type="textarea" placeholder="请输入内容" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="政策内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" maxlength="12000" show-word-limit
            :autosize="{ minRows: 6, maxRows: 10 }" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="政策类型" prop="policyType">
          <el-select v-model="form.policyType" placeholder="请选择政策类型">
            <el-option v-for="item in sys_policy_type" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="失效时间" prop="expirationTime">
          <el-date-picker clearable size="default" v-model="form.expirationTime" type="date" value-format="YYYY-MM-DD"
            placeholder="选择失效时间" style="width: 100%;" popper-class="large-date-picker" />
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="审批意见" prop="message" v-if="showApprovalFields" required>
          <el-input v-model="form.message" type="textarea" placeholder="请输入审批意见" maxlength="200" show-word-limit
            :autosize="{ minRows: 4, maxRows: 4 }" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-if="showApprovalFields">
          <el-button type="primary" @click="handleBtn('PASS')">审批通过</el-button>
          <el-button @click="handleBtn('REJECT')">退回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import {
    ref,
    reactive,
    onMounted,
    computed
  } from 'vue';
  import {
    ElMessage,
    ElMessageBox
  } from 'element-plus';
  import {
    getLeave,
    handle,
    rejectLast,
    taskBack
  } from "@/api/system/leave";
  import {
    anyNodeList
  } from "@/api/flow/execute";
  import {
    useDict
  } from '@/utils/dict';
  // 获取政策类型字典（返回响应式对象）
  const {
    sys_policy_type
  } = useDict('sys_policy_type');
  // 定义 props
  const props = defineProps({
    value: {
      type: String,
      default: "",
    },
    creatorName: {
      type: String,
      default: ""
    },
    businessId: {
      type: String,
      default: "",
    },
    nodeCode: {
      type: String,
      default: ""
    },
    taskId: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    showAnyNode: {
      type: Boolean,
      default: false,
    },
    infoVo: {
      type: Object,
      default: () => ({}),
    },
  });

  // 定义 emits
  const emit = defineEmits(['refresh']);

  // 响应式变量
  const open = ref(false);
  const formRef = ref(null);
  const form = ref({
    message: ''
  })
  const anyNode = ref([]);
  const nodeCode = ref("");
  const flowStatus = ref("");
  const title = ref("办理");
  const showApprovalFields = ref(true);
  const rules = computed(() => ({
    title: [{
      required: true,
      message: '请输入政策标题',
      trigger: 'blur'
    }],
    content: [{
      required: true,
      message: '请输入政策内容',
      trigger: 'blur'
    }],
    policyType: [{
      required: true,
      message: '请选择政策类型',
      trigger: 'change'
    }],
    expirationTime: [{
      required: true,
      message: '请选择失效时间',
      trigger: 'change'
    }],
    // 仅当 showApprovalFields 为 true 时，message 才必填
    message: showApprovalFields.value ? [{
      required: true,
      message: '请输入审批意见',
      trigger: 'blur'
    }] : [] // 不显示时无需校验
  }));
  // 初始化
  onMounted(() => {
    getLeave(props.businessId).then((res) => {
      res.data.policyType = String(res.data.policyType);
      res.data.content = stripTags(res.data.content)
      form.value = res.data
    })
    open.value = true;
  });
  // 新增：去标签工具方法
  const stripTags = (str) => {
    if (typeof str !== 'string') return str;
    return str
        .replace(/<!--[\s\S]*?-->/g, '') // 去除注释标签
        .replace(/<br\s*\/?>/gi, '\n') // 将 <br>、<br/> 转换为换行符 \n
        .replace(/<\/p>/gi, '\n') // 将 </p> 结束标签转换为换行符（可选，根据需求）
        .replace(/<[^>]+>/g, ''); // 去除其他所有标签
  };
  // 表单重置
  const reset = () => {
    form.message = null;
    form.id = null;
    form.type = null;
    form.reason = null;
    form.startTime = null;
    form.endTime = null;
    form.day = null;
    form.instanceId = null;
    form.nodeCode = null;
    form.nodeName = null;
    form.flowStatus = null;
    form.createBy = null;
    form.createTime = null;
    form.updateBy = null;
    form.updateTime = null;
    form.delFlag = null;
    flowStatus.value = "";
    if (formRef.value) {
      formRef.value.resetFields();
    }
  };

  // 取消按钮
  const cancel = () => {
    open.value = false;
    reset();
  };

  const handleBtn = (skipType) => {
    if (formRef.value) {
      formRef.value.validate((valid) => {
        if (!valid) {
          ElMessage.warning("请完善表单信息");
          return;
        }
        const busPolicyContent = {
          policyId: form.value.policyId,
          title: form.value.title,
          content: form.value.content,
          expirationTime: form.value.expirationTime,
          nodeCode: form.value.nodeCode,
          instanceId: form.value.instanceId,
          approveStatus: form.value.approveStatus
        };
        // 调用接口（确保 method 为 put，url 正确）
        handle(busPolicyContent, props.taskId, skipType, form.value.message, form.value.nodeCode, form.value
          .flowStatus).then(
          response => {
            ElMessage.success("办理成功");
            open.value = false;
            emit('refresh');
          }).catch(error => {
          console.error("操作失败原因:", error.response?.data?.msg || error.message);
        });
      });
    }
  };

  // 拿回
  const task = () => {
    if (formRef.value) {
      formRef.value.validate((valid) => {
        if (valid) {
          taskBack(form, props.taskId, form.message, flowStatus.value).then(response => {
            ElMessage.success("拿回到最近办理的任务");
            open.value = false;
            emit('refresh');
          });
        }
      });
    }
  };
</script>